<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Live Streaming Sender</title>
    <script src="https://cdn.socket.io/4.0.0/socket.io.min.js"></script>
</head>
<body>
<video id="localVideo" autoplay></video>
<script>
    // 获取媒体流
    navigator.mediaDevices.getUserMedia({ video: true, audio: true })
        .then(stream => {
            const videoElement = document.getElementById('localVideo');
            videoElement.srcObject = stream;

            // 创建 MediaRecorder 对象
            const mediaRecorder = new MediaRecorder(stream);

            // 当有数据可用时，将数据片段发送到服务器
            mediaRecorder.ondataavailable = event => {
                if (event.data.size > 0) {
                    const blob = new Blob([event.data], { type: 'video/webm' });
                    const data = {
                        type: 'video',
                        payload: Array.from(new Uint8Array(blob.arrayBuffer()))
                    };
                    socket.emit('video', JSON.stringify(data));
                }
            };

            // 创建 WebSocket 连接
            const socket = io('http://127.0.0.1:8081', {
                transports: ['websocket'],
                extraHeaders: {
                    'X-Custom-Header': 'CustomValue'
                }
            });

            socket.on('connect', () => {
                console.log('Connected to server');
                mediaRecorder.start(1000); // 每秒录制一段
            });

            socket.on('disconnect', () => {
                console.log('Disconnected from server');
            });

            socket.on('error', error => {
                console.error('WebSocket error:', error);
            });
        })
        .catch(error => console.error('Error accessing media devices.', error));
</script>
</body>
</html>